<?php

declare(strict_types=1);

namespace App\Model\Config;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Tappable\HigherOrderTapProxy;

/**
 * @property int $id
 * @property int $config_id 配置id
 * @property int $sort  排序
 * @property int $status 状态 1正常 2禁用
 * @property string $data  数据
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 */
class ConfigData extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'config_data';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [
        'config_id',
        'sort',
        'status',
        'data',
    ];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'config_id' => 'integer', 'sort' => 'integer', 'status' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public function setDataAttribute($value): void
    {
        $this->attributes['data'] = json_encode($value);
    }

    public function getDataAttribute($value): array
    {
        return json_decode($value, true);
    }

    /**
     * 获取配置名称
     * @param $value
     * @return HigherOrderTapProxy|mixed|string|null
     */
    public function getConfigNameAttribute($value): mixed
    {
        if (!$this->config_id) return '';
        return Config::query()->where('id', $this->config_id)->value('name');
    }
}
